package com.xiaoshu.disruptor;

import com.lmax.disruptor.RingBuffer;
import com.lmax.disruptor.dsl.Disruptor;
import com.xiaoshu.disruptor.handler.HandlerMethodEvent;
import com.xiaoshu.service.SlaveDoubleWriteRedisTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * code is far away from bug with the animal protecting
 * ┏┓　　　┏┓
 * ┏┛┻━━━┛┻┓
 * ┃　　　　　　　┃
 * ┃　　　━　　　┃
 * ┃　┳┛　┗┳　┃
 * ┃　　　　　　　┃
 * ┃　　　┻　　　┃
 * ┃　　　　　　　┃
 * ┗━┓　　　┏━┛
 * 　　┃　　　┃神兽保佑
 * 　　┃　　　┃代码无BUG！
 * 　　┃　　　┗━━━┓
 * 　　┃　　　　　　　┣┓
 * 　　┃　　　　　　　┏┛
 * 　　┗┓┓┏━┳┓┏┛
 * 　　　┃┫┫　┃┫┫
 * 　　　┗┻┛　┗┻┛
 *
 * @Description : function description
 * ---------------------------------
 * @Author : deane
 * @Date : Create in 2021/3/20 10:31
 * <p>
 * Copyright (C)2013-2021 小树盛凯科技 All rights reserved.
 */
@Component
@Slf4j
public class MessageDisruptorQueue {

    /**
     * ring buffer
     */
    private static RingBuffer<MessageEvent> ringBuffer;
    /**
     * create  Executor  service;
     */
    private ExecutorService executor = new ThreadPoolExecutor(10, 10,
            0L, TimeUnit.MILLISECONDS,
            new LinkedBlockingQueue<>());

    private int bufferSize = 1 * 1024;
    /**
     * Message factory create;
     */
    private MessageEventFactory factory = new MessageEventFactory();
    /**
     * create Disruptor queue;
     */
    private Disruptor<MessageEvent> disruptor = new Disruptor<>(factory, bufferSize, executor);

    /**
     * create  Message {@link Disruptor}
     */
    public MessageDisruptorQueue(HandlerMethodEvent handlerMethodEvent) {
        log.info("start up the disruptor, on time :{} ", System.currentTimeMillis());
        disruptor.handleEventsWith(handlerMethodEvent);
        ringBuffer = disruptor.getRingBuffer();
        disruptor.start();
    }

    /**
     * put the method information into ringBuffer;
     * @param methodInfo
     */
    public void publishEvent(MethodInfoModel  methodInfo) {
        long sequenceID = ringBuffer.next();
        try {
            MessageEvent event = ringBuffer.get(sequenceID);
            event.setMethodInfo(methodInfo);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            ringBuffer.publish(sequenceID);
        }
    }

}
